<?php
class Mysql
{
	var $linkID    = NULL;
	var $host     = "";
	var $database = "";
	var $user     = "";
	var $password = "";
	var $charset = "utf8";
	var $cache_data_dir = "";
	var $queryID = null;
	var $table_field = array();
	
	function __construct($config=array())
	{
		$this->cache_data_dir = SYSPATH . 'data/cache/sql/';
		if(!$config){
			print_r('no db!');exit;
		}
		$this->host     = $config['host'];
		$this->database = $config['name'];
		$this->user     = $config['user'];
		$this->password = $config['password'];
		$this->charset = $config['charset']?$config['charset']:'utf8';
		$this->connect();
		/*if(TIME_ZONE && !IGNORE_MYSQL_TIMEZONE)
		{
			$sql = "SET time_zone = '".TIME_ZONE."'";
			$this->query($sql);
		}*/
	}
	function connect()
	 {
		if (is_null($this->linkID) || !is_resource($this->linkID) || strcasecmp(get_resource_type($this->linkID), "mysql link") <> 0)
		{
			$this->linkID = @mysql_connect($this->host, $this->user, $this->password);
			@mysql_query("SET character_set_connection={$this->charset}, character_set_results={$this->charset}, character_set_client=binary",$this->linkID);
			if($_GET['debugsql']) echo 'connect:'.date('Y-m-d H:i:s').'<br>';
		}
		if (!is_resource($this->linkID) || strcasecmp(get_resource_type($this->linkID), "mysql link") <> 0)
		{
			_e("can not connect to ".$this->host.", ".mysql_error().", ".mysql_errno());
		}
	}
	function reconnect()
	{
		$this->close();
		$this->connect();
	}
	function query($sql)
	{
		$result = null;
		if($sql == "") _e("query string was empty");
		if($this->queryID) $this->queryID = NULL;
		if(!mysql_ping($this->linkID)) $this->reconnect();

		if (!mysql_select_db($this->database, $this->linkID))
		{
			$this->reconnect();
			if (!mysql_select_db($this->database, $this->linkID))
			{
				$err_msg = "sql: $sql\n";
				$err_msg .= "can not use the database " . $this->database . ", " . mysql_error($this->linkID) . ", " . mysql_errno($this->linkID) . "\n";
				$err_msg .= "connection info: {$this->host} {$this->database} {$this->user} \n";
				_e($err_msg);
			}
		}


		$this->queryID = @mysql_query($sql, $this->linkID);
		if(!$this->queryID) _e("query failed: $sql, ".mysql_error().", ".mysql_errno());
		return $this->queryID;
	}
	function close(){
		if($this->linkID){
			return mysql_close($this->linkID);
		}
	}
	function selectdb($name){
		if(mysql_select_db($this->database, $this->linkID)){
			$this->database = $name;
			return true;
		}
		return false;
	}
	function getLastInsertId()
	{
		return @mysql_insert_id($this->linkID);
	}
    function getAll($sql,$keyname="",$cachetime=0)
    {
		$cacheFileName = $this->cache_data_dir.$this->host.$this->database.md5($this->user.$this->password.$sql).$keyname;
		if($cachetime>0){
			if (file_exists($cacheFileName)) {
				if(time()-filemtime($cacheFileName) < $cachetime*60+rand(1,60)){
					return unserialize(file_get_contents($cacheFileName)); 
				}
			}
		}
		if($_GET['debugsql']){
			echo date('Y-m-d H:i:s').' '.$sql.'<br>';
		}
        $res = $this->query($sql);
        if ($res !== false)
        {
            $arr = array();
            while ($row = mysql_fetch_assoc($res))
            {
				if($keyname){
					$arr[$row[$keyname]] = $row;
				}else{
					$arr[] = $row;
				}
            }
			if($cachetime>0) file_put_contents($cacheFileName,serialize($arr));
            return $arr;
        }
        else
        {
            return false;
        }
    }
    function getRow($sql,$cachetime=0)
    {
        if (stripos($sql,'limit')===false)
        {
            $sql = trim($sql . ' LIMIT 1');
        }
		$cacheFileName = $this->cache_data_dir.$this->host.$this->database.md5($this->user.$this->password.$sql);
		if($cachetime>0){
			if (file_exists($cacheFileName)) {
				if(time()-filemtime($cacheFileName) < $cachetime*60+rand(1,60)){
					return unserialize(file_get_contents($cacheFileName)); 
				}
			}
		}
		if($_GET['debugsql']){
			echo $sql.'<br>';
		}
        $res = $this->query($sql);
        if ($res !== false)
        {	
			$res = mysql_fetch_assoc($res);
			if($cachetime>0) file_put_contents($cacheFileName,serialize($res));
            return $res;
        }
        else
        {
            return false;
        }
    }
	function get_table_field($table){
		if(!$this->table_field[$table]){
			$path = SYSPATH."data/cache/table/".str_replace(array(',','.'),'_',$this->host.'_'.$this->database.'_'.$table)."_field.php";
			if(!is_file($path)||time()-filemtime($path)>60*30){
				$field = array();
				$sql = "show columns from ".$table;
				$arr = $this->getAll($sql);
				foreach($arr as $v){
					$field[$v['Field']] = $v['Type'];
				}
				file_put_contents($path,"<?php\n return ".var_export($field, true)."\n?>");
			}
			$this->table_field[$table] = include $path;
		}
	}
	function insert($table,$data){
		$this->get_table_field($table);
		$field = '';
		$vaule = '';
		$i = 0;
		foreach($data as $key=>$v){
			if(!$this->table_field[$table][$key]) continue;
			$v = addslashes($v);
			if($i ==0 ){
				$field .= '`'.$key.'`';
				$vaule .= "'{$v}'";
			}else{
				$field .= ','.'`'.$key.'`';
				$vaule .= ","."'{$v}'";
			}
			$i++;
		}
		$sql = "INSERT INTO {$table} ({$field}) VALUES ({$vaule})";
		return $this->query($sql);
	}
	function update($table,$data,$where){
		$this->get_table_field($table);
		$set = '';
		$i = 0;
		foreach($data as $key=>$v){
			if(!$this->table_field[$table][$key]) continue;
			$v = addslashes($v);
			if($i ==0 ){
				$set .= "set `{$key}` = '{$v}'";
			}else{
				$set .= ","."`{$key}` = '{$v}'";
			}
			$i++;
		}
		$sql = "UPDATE {$table} {$set} WHERE {$where}";
		$this->query($sql);
	}
	function delete($table,$where){
		if(count($where)>0){
		}else{
			return false;
		}
		$wherestr = '';
		foreach($where as $key=>$v){
			if($wherestr){
				$wherestr .= " AND {$key} = '{$v}'";
			}else{
				$wherestr .= " {$key} = '{$v}'";
			}
		}
		$sql = "DELETE FROM {$table} WHERE {$wherestr}";
		$this->query($sql);
	}
}

?>